package com.yw.service.Impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yw.codeManageInfo.domain.CodeConfiguration;
import com.yw.codeManageInfo.domain.CodeManageInfo;
import com.yw.codeManageInfo.dto.AddCodeCentreConfigurationDTO;
import com.yw.codeManageInfo.dto.AddCodeDTO;
import com.yw.codeManageInfo.dto.QueryDTO;
import com.yw.codeManageInfo.vo.CodeManageInfoVO;
import com.yw.mapper.CodeManageMapper;
import com.yw.piliangDTO.StatusDTO;
import com.yw.service.CodeConfigurationService;
import com.yw.service.CodeManageService;
import com.yw.utils.BeanConverter;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CodeManageServiceImpl extends ServiceImpl<CodeManageMapper, CodeManageInfo>
                                    implements CodeManageService {

    @Resource
    private CodeConfigurationService codeConfigurationService;

    @Resource
    private CodeManageMapper codeManageMapper;

    @Override
    public Page<CodeManageInfoVO> pageAllByQuery(QueryDTO queryDTO) { //根据条件分页查询整表
        Page<CodeManageInfo> page = new Page<>(queryDTO.getPageNumber(), queryDTO.getPageSize());
        LambdaQueryWrapper<CodeManageInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(queryDTO.getStatus() != null,CodeManageInfo::getStatus,queryDTO.getStatus())
                .like(queryDTO.getCodeName() != null,CodeManageInfo::getCodeName,queryDTO.getCodeName());
        Page<CodeManageInfo> pageResult = this.page(page,wrapper);
        Page<CodeManageInfoVO> returnPage = new Page<>();
        returnPage.setRecords(BeanConverter.convertList(pageResult.getRecords(),CodeManageInfoVO.class));
        returnPage.setCurrent(pageResult.getCurrent());
        returnPage.setTotal(pageResult.getTotal());
        returnPage.setSize(pageResult.getSize());
        return returnPage;
    }

    @Override
    public AddCodeDTO getConfigurationByCodeId(Integer id){ //根据id查询码值表
        CodeManageInfo one = this.getById(id);
        AddCodeDTO addCodeDTO = new AddCodeDTO();
        addCodeDTO.setCodeName(one.getCodeName());
        addCodeDTO.setCodeDesc(one.getCodeDesc());
        LambdaQueryWrapper<CodeConfiguration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CodeConfiguration::getCodeId,id);
        List<CodeConfiguration> list = codeConfigurationService.list(wrapper);
        ArrayList<AddCodeCentreConfigurationDTO> addCodeCentreConfigurationDTOS = new ArrayList<>();
        for (CodeConfiguration codeConfiguration : list) {
            AddCodeCentreConfigurationDTO addCodeCentreConfigurationDTO = new AddCodeCentreConfigurationDTO();
            addCodeCentreConfigurationDTO.setConfigurationName(codeConfiguration.getConfigurationName());
            addCodeCentreConfigurationDTO.setConfigurationValue(codeConfiguration.getConfigurationValue());
            addCodeCentreConfigurationDTO.setConfigurationMean(codeConfiguration.getConfigurationMean());
            addCodeCentreConfigurationDTOS.add(addCodeCentreConfigurationDTO);
        }
        addCodeDTO.setCodeConfiguration(addCodeCentreConfigurationDTOS);
        return addCodeDTO;
    }

    @Override
    public Boolean addCode(AddCodeDTO addCodeDTO){ //向码表中添加数据
        //定义一个CodeManageInfo类，将接收到的要保存的码表的字段放在其中
        CodeManageInfo codeManageInfo = new CodeManageInfo();
        codeManageInfo.setCodeName(addCodeDTO.getCodeName());
        codeManageInfo.setCodeDesc(addCodeDTO.getCodeDesc());
        codeManageInfo.setStatus(0);
        codeManageInfo.setCreateTime(LocalDateTime.now());
        codeManageInfo.setUpdateTime(LocalDateTime.now());
        //根据需求规则生成码表编号
        LambdaQueryWrapper<CodeManageInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(CodeManageInfo::getId).last("LIMIT 1");;
        CodeManageInfo one = this.getOne(wrapper);
        String numString = one.getCode().substring(3, 8);
        Integer i = Integer.valueOf(numString);
        int num = i + 1;
        String resultCode = null;
        switch (String.valueOf(num).length()){
            case 1: resultCode = "MZB0000" + num;break;
            case 2: resultCode = "MZB000" + num;break;
            case 3: resultCode = "MZB00" + num;break;
            case 4: resultCode = "MZB0" + num;break;
            case 5: resultCode = "MZB" + num;break;
        }
        codeManageInfo.setCode(resultCode);
        //添加子表编码配置表数据，因为可以有多条，所以用集合来存储
        List<AddCodeCentreConfigurationDTO> codeConfiguration = addCodeDTO.getCodeConfiguration();
        //创建要向表中保存的CodeConfiguration类型集合，循环遍历将要保存的数据放入其中
        ArrayList<CodeConfiguration> newCodeConfiguration = new ArrayList<>();
        for (AddCodeCentreConfigurationDTO addCodeCentreConfigurationDTO : codeConfiguration) {
            CodeConfiguration newConfiguration= new CodeConfiguration();
            newConfiguration.setCreateTime(LocalDateTime.now());
            newConfiguration.setUpdateTime(LocalDateTime.now());
            newConfiguration.setConfigurationName(addCodeCentreConfigurationDTO.getConfigurationName());
            newConfiguration.setConfigurationMean(addCodeCentreConfigurationDTO.getConfigurationMean());
            newConfiguration.setConfigurationValue(addCodeCentreConfigurationDTO.getConfigurationValue());
            newConfiguration.setCodeId(one.getId()+1);
            newCodeConfiguration.add(newConfiguration);
        }
        boolean b = codeConfigurationService.saveBatch(newCodeConfiguration);
        boolean a = this.save(codeManageInfo);
        if (a && b){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public Boolean updateStatic(Integer id) { //修改状态
        CodeManageInfo one = this.getById(id);
        switch (one.getStatus()){
            case 0, 2:
                one.setStatus(1);break;
            case 1:
                one.setStatus(2);break;
        }
        if(this.updateById(one)){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Boolean updateCode(Integer id,AddCodeDTO addCodeDTO) {
        //定义一个CodeManageInfo类，将接收到的要保存的码表的字段放在其中
        CodeManageInfo codeManageInfo = new CodeManageInfo();
        codeManageInfo.setId(id);
        codeManageInfo.setCodeName(addCodeDTO.getCodeName());
        codeManageInfo.setCodeDesc(addCodeDTO.getCodeDesc());
        codeManageInfo.setUpdateTime(LocalDateTime.now());
        CodeManageInfo one = this.getById(id);
        codeManageInfo.setStatus(one.getStatus());
        codeManageInfo.setCode(one.getCode());
        codeManageInfo.setCreateTime(one.getCreateTime());
        //添加子表编码配置表数据，因为可以有多条，所以用集合来存储
        List<AddCodeCentreConfigurationDTO> codeConfiguration = addCodeDTO.getCodeConfiguration();
        //创建要向表中保存的CodeConfiguration类型集合，循环遍历将要保存的数据放入其中
        LambdaQueryWrapper<CodeConfiguration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CodeConfiguration::getCodeId,id);
        codeConfigurationService.remove(wrapper);
        ArrayList<CodeConfiguration> newCodeConfiguration = new ArrayList<>();
//        List<CodeConfiguration> codeConfigurations = codeConfigurationService.listByCodeId(one.getId());
        for (AddCodeCentreConfigurationDTO addCodeCentreConfigurationDTO : codeConfiguration) {
            CodeConfiguration newConfiguration= new CodeConfiguration();
            newConfiguration.setCreateTime(LocalDateTime.now());
            newConfiguration.setUpdateTime(LocalDateTime.now());
            newConfiguration.setConfigurationName(addCodeCentreConfigurationDTO.getConfigurationName());
            newConfiguration.setConfigurationMean(addCodeCentreConfigurationDTO.getConfigurationMean());
            newConfiguration.setConfigurationValue(addCodeCentreConfigurationDTO.getConfigurationValue());
            newConfiguration.setCodeId(one.getId());
            newCodeConfiguration.add(newConfiguration);
        }
        boolean b = codeConfigurationService.saveOrUpdateBatch(newCodeConfiguration);
        boolean a = this.updateById(codeManageInfo);
        if (a && b){//三个条件都满足，则修改成功
            return true;
        }else{
            return false;
        }
    }

    //批量发布或停用
    @Override
    public Boolean batch(StatusDTO statusDTO) {
        return codeManageMapper.batch(statusDTO);
    }

    //下载
    public byte[] exportDataToExcel(){
        // 获取数据
        List<CodeManageInfo> dataList = this.list();

        // 创建输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // 使用 EasyExcel 写入数据
        EasyExcel.write(bos, CodeManageInfo.class).sheet("Data").doWrite(dataList);

        return bos.toByteArray();
    }

    @Override
    public List<String> codeNames() {
        List<CodeManageInfo> list = this.list();
        ArrayList<String> strings = new ArrayList<>();
        for (CodeManageInfo codeManageInfo : list) {
            strings.add(codeManageInfo.getCodeName());
        }
        return strings;
    }


}
